<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="false"
			:requestApi="api.GetCategoryDtoPageApi"
			:dataCallback="dataCallback"
		>
			<template #tableHeader>
				<el-button type="primary" :icon="CirclePlus" @click="handleEdit('新增')">新建分类</el-button>
			</template>
			<template #isEnable="scope">
				<el-tag :type="scope.row.isEnable ? 'success' : 'danger'">
					{{ scope.row.isEnable ? "启用" : "禁用" }}
				</el-tag>
			</template>
			<template #operation="scope">
				<el-space wrap>
					<el-tag style="cursor: pointer" @click="handleEdit('编辑', scope.row)"> 编辑 </el-tag>

					<el-tag @click="handleDelete(scope.row.id)" style="cursor: pointer" type="danger"> 删除 </el-tag>
				</el-space>
			</template>
		</proTable>
		<el-dialog v-model="addoreditVisible" @close="handleref" width="850px" :title="titleValue">
			<el-form
				ref="ruleFormRef"
				:model="addOrUpdateForm"
				:rules="rules"
				label-width="auto"
				label-position="left"
				width="50%"
				class="demo-ruleForm"
				status-icon
			>
				<el-form-item label="分类名称：" prop="name">
					<el-input style="width: auto" v-model="addOrUpdateForm.name" placeholder="请输入" />
				</el-form-item>
				<el-form-item prop="parentId" label="分类级别：">
					<!-- <el-select v-model="addOrUpdateForm.parentId" placeholder="请选择">
						<el-option v-for="item in categoryData" :label="item.name" :value="item.id" :key="item.id" />
					</el-select> -->
					<el-cascader
						v-model="addOrUpdateForm.parentId"
						:options="categoryData"
						:props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
					/>
				</el-form-item>
				<el-form-item label="状态" prop="isEnable">
					<el-radio-group v-model="addOrUpdateForm.isEnable">
						<el-radio :label="true">启用</el-radio>
						<el-radio :label="false">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleref">取消</el-button>
					<el-button type="primary" @click="handleSubmit(ruleFormRef)"> 保存 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="logs">
import { ref, computed, reactive } from "vue";
import api from "@/api/modules/category";
import { ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus } from "@element-plus/icons-vue";
import proTable from "@/components/ProTable/index.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { GlobalStore } from "@/stores";
const globalStore = GlobalStore();
const isPlatform = globalStore.isPlatform;
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
// 表格编辑时弹窗和保存
const addoreditVisible = ref(false);
// 弹窗标题
const titleValue = ref("新建分类");
/**添加或更新常量 */
const addOrUpdateForm = reactive({
	id: "",
	name: "",
	parentId: "",
	isEnable: true
});
interface selectItem {
	id: string | null;
	name: string;
}
const categoryData = ref<selectItem[]>([]);
const tranListToTreeData = (list: Array<any>) => {
	//处理扁平数据，转树形
	let treeList: Array<any> = [];
	let map: any = {};
	list.forEach(item => {
		item.children = [];
		map[item.id] = item;
	});
	list.forEach(item => {
		const res = map[item.parentId as string];
		if (res) {
			res.children.push(item);
		} else {
			treeList.push(item);
		}
	});
	return treeList;
};
/**获取资讯分类列表 */
const getCategorys = async (id: string, companyId: string) => {
	categoryData.value = [];
	let { result } = await api.GetAllCategorysApi(id, companyId);
	let { data } = result as any;
	if (!data) {
		categoryData.value = [{ name: "一级分类", id: "1" }];
	}
	let newData = tranListToTreeData(data);
	categoryData.value = [{ name: "一级分类", id: "1" }, ...newData];
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.totalCount
	};
};

const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
	name: [
		{ required: true, message: "标题不能为空", trigger: "blur" },
		{ max: 50, message: "标题最大长度不能超过50", trigger: "blur" }
	],
	parentId: [{ required: true, message: "请选择分类", trigger: "change" }],
	isEnable: [{ required: true, message: "请选择分类", trigger: "change" }]
});

const handleref = () => {
	addoreditVisible.value = false;
	addOrUpdateForm.name = "";
	addOrUpdateForm.parentId = "";
	addOrUpdateForm.id = "";
};

const handleEdit = async (str: string, res: any = null) => {
	if (str === "新增") {
		titleValue.value = "新建分类";
		addoreditVisible.value = true;
		addOrUpdateForm.parentId = "";
		getCategorys("", "");
		return;
	}
	titleValue.value = "编辑分类";
	addoreditVisible.value = true;
	let { id } = res;
	api.GetByIdCategorysApi(id).then((res: any) => {
		if (!res.result.isSuccess) {
			return;
		}
		getCategorys(id, res.result.data.companyId || "");
		addOrUpdateForm.id = id;
		addOrUpdateForm.name = res.result.data.name;
		addOrUpdateForm.parentId = res.result.data.parentId || "1";
		addOrUpdateForm.isEnable = res.result.data.isEnable;
	});
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (valid) {
			addOrUpdateForm.parentId =
				addOrUpdateForm.parentId == "1" ? "" : addOrUpdateForm.parentId[addOrUpdateForm.parentId.length - 1];
			if (addOrUpdateForm.id == "") {
				api.AddCategoryApi(addOrUpdateForm).then((res: any) => {
					if (!res.success) {
						return ElMessage.error("添加失败");
					}
					ElMessage.success("添加成功");
					proTableRef.value.getTableList();
					handleref();
				});
			} else {
				api.UpdateCategoryApi(addOrUpdateForm).then((res: any) => {
					if (!res.success) {
						return ElMessage.error("更新失败");
					}
					ElMessage.success("更新成功");
					proTableRef.value.getTableList();
					handleref();
				});
			}
		}
	});
};
// 表格配置项
let columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{ prop: "companyName", label: "所属商户" },
		{ prop: "name", label: "分类名称" },
		{ prop: "parentName", label: "所属分类" },
		{ prop: "createTime", label: "创建时间" },
		{ prop: "createUserName", label: "创建人" },
		{ prop: "isEnable", label: "状态" },
		{
			prop: "Keywords",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入关键字" } }
		},
		{ prop: "operation", label: "操作", width: 200, fixed: "right" }
	];
	if (!isPlatform) {
		data = data.filter(i => i.prop != "companyName");
		return data;
	}
	return data;
});
// 删除操作
const handleDelete = async (index: string) => {
	// 二次确认删除
	await ElMessageBox.confirm("确定要删除吗？", "提示", {
		type: "warning"
	});
	let { result } = await api.UpdateDeleteCategoryApi({ Id: index });
	if (result.code != 200) {
		ElMessage.error(result.message);
		return;
	}
	ElMessage.success("删除成功");
	proTableRef.value.getTableList();
};
</script>
